package base

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path"
	"runtime"
	"strings"
)

func RecursiveReadProtoFiles(dir string, pre string) []string {
	files, err := ioutil.ReadDir(dir)
	if os.IsNotExist(err) {
		log.Fatalf("Read Dir %s failure: %s\n", dir, err.Error())
	}
	reply := make([]string, 0, len(files))
	for _, f := range files {
		if f.IsDir() {
			reply = append(reply, RecursiveReadProtoFiles(path.Join(dir, f.Name()), f.Name())...)
		}
		if strings.HasSuffix(f.Name(), ".proto") {
			reply = append(reply, path.Join(pre, f.Name()))
		}
	}
	return reply
}

func ReadProtoFiles(dir string) []string {
	return RecursiveReadProtoFiles(dir, "")
}

func GetProtoAuthLanguagePlugin(language string) string {
	if runtime.GOOS == "windows" {
		log.Println("Windows Please specify manually")
		return ""
	}
	plugin := fmt.Sprintf("grpc_%s_plugin", strings.ToLower(language))
	by := &bytes.Buffer{}
	cw := exec.Command("which", plugin)
	cw.Stdout = by
	cw.Stderr = os.Stderr
	if err := cw.Run(); err != nil {
		panic(err)
	}
	return strings.TrimSpace(by.String())
}

func GenerateAuthCode(protoPath, thirdDir string, files []string, language string) {
	phpPlugin := GetProtoAuthLanguagePlugin(language)
	c := exec.Command("protoc", append([]string{
		"--proto_path=" + protoPath,
		"--proto_path=" + thirdDir + "/third_party",
		"--php_out=.",
		"--grpc_out=.",
		"--plugin=protoc-gen-grpc=" + phpPlugin,
	}, files...)...)
	c.Stdout = os.Stdout
	c.Stderr = os.Stderr
	if err := c.Run(); err != nil {
		panic(err)
	}
	for _, v := range files {
		log.Printf("%s success", v)
	}
}
